package iText;

import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.listener.FilteredTextEventListener;
import com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy;
import com.itextpdf.kernel.pdf.canvas.parser.filter.TextRegionEventFilter;

import java.io.IOException;

public class ITextTextExtractor {

    public static String extractTextByCoordinates(String filePath, int pageNumber, Rectangle rect) throws IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(filePath));
        PdfPage page = pdfDoc.getPage(pageNumber);

        System.out.println("Processing Page: " + pageNumber);
        System.out.println("Page Size: " + page.getPageSize());
        System.out.println("Target Rectangle: " + rect);

        TextRegionEventFilter filter = new TextRegionEventFilter(rect);
        LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();

        PdfCanvasProcessor parser = new PdfCanvasProcessor(new FilteredTextEventListener(strategy, filter));
        parser.processPageContent(page);

        String text = strategy.getResultantText();
        System.out.println("Extracted Text: " + text);

        pdfDoc.close();
        return text;
    }

    public static void main(String[] args) {
        try {
            String filePath = "D:\\test.pdf";
            int pageNumber = 1; // 提取第几页
            Rectangle rect = new Rectangle(100, 200, 100, 50); // 定义区域 (x, y, width, height)

            String text = extractTextByCoordinates(filePath, pageNumber, rect);
            System.out.println("Final Extracted Text: " + text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}